#pragma once
#include <string>
#include <windows.h>
using namespace std;



#define LEVEL_DBG		0
#define LEVEL_INFO	    1
#define LEVEL_EMERGENCY	2
#define LEVEL_SCHEDULE 4
#define LEVEL_DELAYINFO 5

#define	TRACE_TO_DEBUGER 1
#define	TRACE_TO_STDOUT  2
#define	TRACE_TO_FILE	 4

#define MAX_TRACE_ENTRY_LENGTH 512
//#define LOG_WORK
class CFormativeTrace
{
public:
	private:
	FILE *m_pLog;

public:
	CFormativeTrace(const char * strPath)
	{
#ifdef LOG_WORK
		int nRes = fopen_s(&m_pLog ,strPath,"w+");
		if(0==nRes)
		{
			
		}
		else
		{
			printf("Error %d \n",nRes);
			m_pLog=NULL;
		}
#endif
	};
	~CFormativeTrace(void)
	{
		if(NULL!=m_pLog)
		{
			fclose(m_pLog);
		}
	};
	inline void Log(const unsigned nDest,const unsigned nTime, const int nOwnerId,const unsigned nLevel,const char *pFormat,...)
	{
#ifdef LOG_WORK
		va_list marker;
		va_start( marker, pFormat );
		Log(nDest,nTime,nOwnerId,nLevel,pFormat,marker);
		va_end( marker );
#endif
	};
	inline void Log(const unsigned nDest,const unsigned nTime, const int nOwnerId,const unsigned nLevel,const char *pFormat,va_list marker)
	{
#ifdef LOG_WORK
		if(NULL!=m_pLog||
			(nDest&TRACE_TO_FILE)==0
			)
		{
			char buf[MAX_TRACE_ENTRY_LENGTH];
			sprintf_s(buf,MAX_TRACE_ENTRY_LENGTH,"Time:%u, Owner:%d, Level:%u,  ",nTime,nOwnerId,nLevel);

			char buf2[MAX_TRACE_ENTRY_LENGTH];
			vsnprintf_s(buf2,MAX_TRACE_ENTRY_LENGTH-2-strlen(buf),MAX_TRACE_ENTRY_LENGTH-2-strlen(buf),pFormat,marker);
			int nEnd=strlen(buf)-1;
			strcat_s(buf,MAX_TRACE_ENTRY_LENGTH-2,buf2);
			while(buf[nEnd]=='\n'||buf[nEnd]=='\r')
			{
				buf[nEnd]=0;
				nEnd--;
			}
			strcat_s(buf,MAX_TRACE_ENTRY_LENGTH,"\r\n");
			if((nDest&TRACE_TO_STDOUT)!=0)
			{
				printf_s(buf);
			}
			if((nDest&TRACE_TO_FILE)!=0)
			{
				fprintf_s(m_pLog,buf);
			}
			if((nDest&TRACE_TO_DEBUGER)!=0)
			{
				OutputDebugStringA(buf);
			}
		}
#endif
	};
	
};
